package com.george.controller;


import cn.hutool.core.util.ObjectUtil;
import com.george.entity.Result;
import com.george.entity.StatusCode;
import com.george.model.dto.ResourceListDto;
import com.george.model.dto.ResourceTreeDto;
import com.george.model.entity.Resources;
import com.george.model.query.ResourceQueryDto;
import com.george.service.IResourcesService;
import com.george.util.JwtUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 * 菜单资源表 前端控制器
 * </p>
 *
 * @author George Chan
 * @since 2019-09-28
 */
@RestController
@CrossOrigin
@RequestMapping("/api/resources")
public class ResourcesController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final JwtUtil jwtUtil;
    private final IResourcesService resourcesService;

    @Autowired
    public ResourcesController(JwtUtil jwtUtil, IResourcesService resourcesService) {
        this.jwtUtil = jwtUtil;
        this.resourcesService = resourcesService;
    }

    /**
     * 保存资源数据
     *
     * @param resources 数据对象
     * @return 操作结果
     */
    @PostMapping("/save")
    public Result save(@RequestBody Resources resources) {
        boolean res = resourcesService.saveResouceData(resources);
        if (!res) {
            return new Result(false, StatusCode.ERROR, "操作失败");
        }
        return new Result(true, StatusCode.OK, "操作成功！");
    }

    /**
     * 获取资源列表
     *
     * @param page  页面
     * @param limit 每页数据条数
     * @param name 资源名称或编码
     * @param limit 资源的id
     * @return 数据集合
     */
    @GetMapping("/list")
    public Result list(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
                       @RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "parentId", required = false) Integer parentId) {
        ResourceQueryDto query = new ResourceQueryDto();
        if (StringUtils.isNotEmpty(name)) {
            query.setName(name);
        }
        if (ObjectUtil.isNotNull(parentId)) {
            query.setId(parentId);
        }
        PageInfo<ResourceListDto> pageInfo = resourcesService.findResouceList(page, limit, query);
        return new Result(true, StatusCode.OK, "操作成功！", pageInfo.getList(), pageInfo.getTotal());
    }

    /**
     * 获取资源树
     * @param name 资源名称或编码
     * @return 返回资源数据
     */
    @GetMapping("/tree")
    public Result tree(@RequestParam(value = "name", required = false) String name) {
        List<ResourceTreeDto> treeList = resourcesService.findResourceTreeData(name);
        return new Result(true, StatusCode.OK, "查询成功！", treeList);
    }
}

